#include "apimanager.h"
#include <QtNetwork>


Q_GLOBAL_STATIC(ApiManager, apiManager)

ApiManager::ApiManager(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager();
}

ApiManager *ApiManager::GetInstance()
{
    return  apiManager;
}

void ApiManager::httpError(QNetworkReply::NetworkError err)
{
    qDebug() << "httpError http Error =" << err;
//    emit sig_serverError("服务器错误");
}

QJsonArray ApiManager::parseItemList(QString itemList)
{
    QStringList lines = itemList.split("#EXTINF:-1 ");

    for (int i = 0; i < lines.length(); i++) { // 节目预告信息
        if (lines[i].contains("#EXTM3U ")) {
            lines.removeAt(i);
            break;
        }
    }

    QJsonArray result;
    for (int i = 0; i < lines.length(); i++) { // 节目列表
        QStringList itemInfos = lines[i].split("\n");
        QJsonObject obj;
        QStringList itemDesc = itemInfos[0].split(" ");

        for (int j = 0; j < itemDesc.length(); j++) {
            if (itemDesc[j].contains("group-title")) {
                QStringList groupInfo = itemDesc[j].split(",");
                obj["name"] = groupInfo[1];
            }
        }

        if (itemInfos[1].isEmpty()) {
            continue;
        }

        obj["source"] = itemInfos[1];

        result.append(obj);
    }

    return result;
}

void ApiManager::getLiveResource()
{
    qDebug()<<"QSslSocket="<<QSslSocket::sslLibraryBuildVersionString();
    qDebug() << "OpenSSL支持情况:" << QSslSocket::supportsSsl();

    QNetworkRequest request(QUrl("https://live.fanmingming.com/tv/m3u/global.m3u"));
    QNetworkReply *reply = manager->get(request);

    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(httpError(QNetworkReply::NetworkError)));
    connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();

            emit sig_getLiveResourceDone(parseItemList(QString(data)));
        } else {
            qDebug() << "网络请求失败:" << reply->errorString();
        }

        reply->deleteLater();
    });
}
